<template>
    <div class="content">
        <div class="header-content">
            <div class="btn">
                <!-- <el-button type="danger" size="mini" @click="handleButton('delete')"> 删除</el-button> -->

                <el-button type="primary" size="mini" @click="handleButton('send')">发送</el-button>
                <el-button type="danger" size="mini" @click="handleButton('close')"> 关闭</el-button>
            </div>
            <el-form id="header-query" label-width="110px" ref="searchParam" :model="searchParam">
                <el-form-item label="模板类型" prop="noticeType">
                    <el-select v-model="searchParam.noticeType" filterable size="mini" clearable>
                        <el-option v-for="(value, key) in Dict.noticeTypePojo" :key="key" :label="value" :value="key"> </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="接收角色" prop="notifiers">
                    <el-select
                        v-model="searchParam.notifiers"
                        multiple
                        clearable
                        filterable
                        collapse-tags
                        size="mini"
                        @change="changeAccountControlValue(searchParam.notifiers, 'notifiers')"
                    >
                        <el-option
                            v-for="item in roleList"
                            :key="item.roleCode"
                            :label="item.roleCode + ' ' + item.roleName"
                            :value="item.roleCode"
                        ></el-option>
                    </el-select>
                    <!-- <el-input size="mini" v-model="searchParam.notifier" clearable></el-input> -->
                </el-form-item>
                <el-form-item label="接收用户" prop="noticeUsers">
                    <!-- <el-input size="mini" v-model="searchParam.noticeUser" clearable></el-input> -->
                    <el-select
                        v-model="searchParam.noticeUsers"
                        multiple
                        clearable
                        filterable
                        collapse-tags
                        size="mini"
                        @change="changeAccountControlValue(searchParam.noticeUsers, 'noticeUsers')"
                    >
                        <el-option
                            v-for="item in userList"
                            :key="item.userCode"
                            :label="item.userName + ' ' + item.userNickName"
                            :value="item.userCode"
                        ></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="发送状态" prop="sendStatus">
                    <el-select v-model="searchParam.sendStatus" multiple clearable filterable collapse-tags size="mini">
                        <el-option v-for="(value, key) in Dict.sendStatusPojo" :key="key" :label="value" :value="key"> </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div>
                <el-button type="primary" size="mini" @click="handleButton('search')">查询</el-button>
            </div>
        </div>
        <div class="noOpened">
            <RiskTableP
                :ref="'risk-table-' + type"
                :tableConfig="tableConfig"
                :tableData="tableData"
                :column="tableColumns"
                :paging="paging"
                v-loading="tableLoading"
                @page-change="getTableData"
            >
                <template #entryCodeCount="scope">
                    <a href="javascript:;" @click="handleBtnEntryNum(scope.row)">{{ scope.row.entryCodeCount }}</a>
                </template>
            </RiskTableP>
        </div>

        <!-- 发送 -->
        <yh-dialog
            title="角色/用户选择"
            :visible.sync="sendAgainVisible"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="560px"
            drag
        >
            <el-form label-width="120px" ref="sendForm" :model="sendForm" class="form">
                <el-form-item label="选择用户" prop="noticeUser">
                    <el-select
                        v-model="sendForm.noticeUser"
                        filterable
                        clearable
                        collapse-tags
                        multiple
                        size="mini"
                        @change="changeAccountControlValue(sendForm.noticeUser, 'noticeUserTemp')"
                    >
                        <el-option
                            v-for="item in userListTemp"
                            :key="item.userCode"
                            :label="item.userName + ' ' + item.userNickName"
                            :value="item.userCode"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="抄送用户" prop="noticeCCuser">
                    <el-select
                        v-model="sendForm.noticeCCuser"
                        filterable
                        clearable
                        collapse-tags
                        multiple
                        size="mini"
                        @change="changeAccountControlValue(sendForm.noticeCCuser, 'noticeCCuser')"
                    >
                        <el-option
                            v-for="item in userListTemp2"
                            :key="item.userCode"
                            :label="item.userName + ' ' + item.userNickName"
                            :value="item.userCode"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="选择角色" prop="notifier">
                    <el-select
                        v-model="sendForm.notifier"
                        filterable
                        clearable
                        collapse-tags
                        multiple
                        size="mini"
                        @change="changeAccountControlValue(sendForm.notifier, 'notifierTemp')"
                    >
                        <el-option
                            v-for="item in roleListTemp"
                            :key="item.roleCode"
                            :label="item.roleCode + ' ' + item.roleName"
                            :value="item.roleCode"
                        ></el-option>
                    </el-select>
                </el-form-item>
                1.对于“发送成功”的记录,如果选择了新用户、角色，则按新用户、角色发送并生成新记录。如无选择，按原记录中用户/角色发送，同时也生成新记录。
                <br />
                2.对于“待发送”的，则取原用户与选择用户的并集，新用户则生成新记录，源用户则按原记录发送；
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="handleDialogButton('cancel')"> 取 消 </el-button>
                <el-button size="mini" type="primary" @click="handleDialogButton('confirm')">
                    确 定
                </el-button>
            </div>
        </yh-dialog>

        <!-- 条目明细 -->
        <yh-dialog
            title="条目明细"
            :visible.sync="entryDetailVisible"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="900px"
            drag
            class="entry-detail"
            v-if="entryDetailVisible"
        >
            <RiskTableP
                :tableConfig="tableConfig"
                :tableData="entryDetailList"
                :column="entryDetailColumns"
                :paging="pagingEntryDetail"
                @page-change="pagechangeEntryDetail"
                v-loading="entryTableLoading"
            >
            </RiskTableP>

            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="handleDialogButton('entry-detail-cancel')"> 取 消 </el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { DaySendListReqVO } from '../../vo/warning-notice';
import API from '../../api/warning-notice';
import { PageVO, TableConfigVO, VueObject } from '@/common/vo';
import WarningNotice from '../../dict/warning-notice';
import { changeOptions, dateFormat, numberFormat, timeFormat, unitShow } from '@/utils/tools';
import XEUtils from 'xe-utils';
import * as moment from 'moment';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({ name: 'DaySendList', components: { RiskTableP } })
export default class DaySendList extends Vue {
    @Prop() activeValue: string;
    Dict = new WarningNotice();
    tableColumns: any = [
        {
            type: 'checkbox',
            selectedAll: false,
            fixed: 'left',
            align: 'center',
            width: 50,
        },
        {
            title: '发送批次号',
            field: 'recordBatchId',
            minWidth: 100,
        },
        {
            title: '规则编码',
            field: 'ruleId',
            minWidth: 90,
        },
        {
            title: '规则名称',
            field: 'ruleName',
            minWidth: 120,
        },
        {
            title: '模板类型',
            field: 'noticeType',
            minWidth: 110,
            render: value => this.Dict.noticeTypePojo[value],
        },
        {
            title: '数据生成类型',
            field: 'calcType',
            minWidth: 120,
            render: value => this.Dict.calcTypePojo[value],
        },
        {
            title: '通知日历类型',
            field: 'dateType',
            minWidth: 120,
            render: value => this.Dict.dateTypePojo[value],
        },
        {
            title: '条目数',
            field: 'entryCodeCount',
            minWidth: 80,
            align: 'center',
        },
        {
            title: '计划发送时点',
            field: 'startTime',
            minWidth: 130,
            render: value => timeFormat(value, false, 'HH:mm', 'HHmm') || '--',
        },
        {
            title: '执行方式',
            field: 'executionMethod',
            minWidth: 90,
            render: value => this.Dict.executionMethodPojo[value],
        },
        {
            title: '接收角色',
            field: 'notifierName',
            minWidth: 90,
        },
        {
            title: '接收用户',
            field: 'noticeUserName',
            minWidth: 90,
        },
        {
            title: '抄送用户',
            field: 'noticeCCuserName',
            minWidth: 90,
        },
        // {
        //     title: '最近一次发送时间',
        //     field: 'sendDate',
        //     minWidth: 150,
        //     render: (value, row) => (dateFormat(value) + ' ' + timeFormat(row.sendTime)).trim(),
        // },
        {
            title: '发送人',
            field: 'operatorNo',
            minWidth: 90,
        },
        {
            title: '发送时间',
            field: 'sendDate',
            minWidth: 150,
            render: (value, row) => (dateFormat(value) + ' ' + timeFormat(row.sendTime)).trim(),
        },
        {
            title: '发送状态',
            field: 'sendStatus',
            minWidth: 90,
            render: value => this.Dict.sendStatusPojo[value],
        },
    ];

    requestTableMethodName: any = API.daySendList;

    isFirst: boolean = true;

    type: string = 'day-send';

    tableConfig: TableConfigVO = {
        rowKey: 'recordId',
    };
    tableData: any[] = [
        {
            recordId: '1221',
            entryCodeCount: 20,
            sendStatus: '0',
            noticeType: '1',
        },
        {
            recordId: '1231',
            entryCodeCount: 20,
            sendStatus: '1',
            noticeType: '2',
        },
    ];

    paging: PageVO = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };

    pagingEntryDetail: PageVO = {
        currentPage: 1,
        pageSize: 10,
        total: 0,
    };

    searchParam: DaySendListReqVO = {
        noticeType: '',
        notifiers: [],
        noticeUsers: [],
        sendStatus: ['0'],
    };

    sendForm: any = {
        notifier: [],
        noticeCCuser: [],
        noticeUser: [],
    };

    sendAgainVisible: boolean = false;
    entryDetailVisible: boolean = false;
    entryDetailList: any[] = [];
    entryTableLoading: boolean = false;

    entryDetailColumns: any[] = [
        {
            field: 'tradeDate',
            title: '估值日期',
            minWidth: 100,
            render: value => dateFormat(value),
        },
        {
            field: 'fundProductCodeStr',
            title: '产品代码(名称)',
            minWidth: 130,
        },
        {
            field: 'clauseCode',
            title: '合规条款',
            minWidth: 90,
        },
        {
            field: 'entryCode',
            title: '条目编号',
            minWidth: 90,
        },
        {
            field: 'entryName',
            title: '系统配置条目',
            minWidth: 120,
        },
        {
            field: 'result',
            title: '计算值',
            // render: (value, row) => {
            //     return row.result != undefined ? numberFormat(row.result, row.unit) + unitShow(row.unit) : '--';
            // },
            minWidth: 100,
        },
        {
            title: '控制阈值',
            field: 'thresholdValue',
            minWidth: 100,
            // render: (value, row) => (value != undefined ? this.Dict.compareTypeStrPojo[row.compareType] + numberFormat(value, 2) : '--'),
        },
        { title: '连续超限天数', field: 'prohibitionDate', minWidth: 120 },
        { title: '超限事件分布', field: 'adjustProgerss', minWidth: 120 },
        //  render: value => this.Dict.adjustProgerssPojo[value]
        { title: '指标状态', field: 'triggerType', minWidth: 100 },
        // render: value => this.Dict.triggerTypePojo[value]
    ];

    tableConfigEntry: TableConfigVO = {
        rowKey: 'serialNo',
    };

    private userList = []; // 用户列表

    private roleList = []; // 角色列表

    private userListTemp = []; // 用户列表

    private userListTemp2 = []; // 抄送用户列表

    private roleListTemp = []; // 角色列表

    tableLoading: boolean = false;
    toEntryInfo: any = {
        noticeType: '',
        recordId: '',
    };
    @Watch('activeValue', { immediate: true })
    async handleActiveValue() {
        if (this.activeValue === 'day-send-list') {
            if (this.isFirst) {
                this.getTableData();
                this.isFirst = false;
                this.getRoleInfo();
                this.getUserList();
            }
        }
    }

    // 获取通知角色数据
    private getRoleInfo(): void {
        this.$axios.get('/role/query/all').then((res: any) => {
            this.roleList = [];
            for (let item of res) {
                if (item.sourceType === '1') {
                    this.roleList.push(item);
                }
            }
            this.roleListTemp = JSON.parse(JSON.stringify(this.roleList));
        });
    }

    private getUserList(): void {
        this.$axios.get('/userManage/user/list').then((res: any) => {
            if (res) {
                this.userList = res;
                this.userListTemp = JSON.parse(JSON.stringify(res));
                this.userListTemp2 = JSON.parse(JSON.stringify(res));
            }
        });
    }

    // 下拉框数据置顶
    private changeAccountControlValue(val: any = [], field): void {
        if (field == 'noticeUsers') {
            this.userList = changeOptions(val, this.userList, 'userCode');
        } else if (field == 'notifiers') {
            this.roleList = changeOptions(val, this.roleList, 'roleCode');
        } else if (field == 'noticeUserTemp') {
            this.userListTemp = changeOptions(val, this.userListTemp, 'userCode');
        } else if (field == 'notifierTemp') {
            this.roleListTemp = changeOptions(val, this.roleListTemp, 'roleCode');
        } else if (field == 'noticeCCuser') {
            this.userListTemp2 = changeOptions(val, this.userListTemp2, 'userCode');
        }
    }

    /**
     * 操作行
     */
    async handleButton(type) {
        if (type == 'send' || type == 'close' || type == 'delete') {
            let name = '';
            let requestName;
            if (type == 'send') {
                name = '发送';
            } else if (type == 'close') {
                name = '关闭';
                requestName = API.sendClose;
            } else if (type == 'delete') {
                name = '删除';
                requestName = API.sendDelete;
            }
            let checkedRows = (this.$refs['risk-table-' + this.type] as VueObject).checkedRows || [];
            if (checkedRows.length < 1) {
                this.yh_message_info(`请先勾选需${name}的数据！`);
                return;
            }

            let params = {};
            if (type == 'delete') {
                params = { recordIds: checkedRows.map(item => item.recordId) };
                requestName(params)
                    .then(() => {
                        this.yh_message_success(name + '成功');
                        this.paging.currentPage = 1;
                        this.getTableData();
                    })
                    .finally(() => {
                        // 清除导出时列表勾选项
                        this.$nextTick(() => {
                            (this.$refs['risk-table-' + this.type] as any).resetCheckRowKeys();
                        });
                    });
            } else if (type == 'send') {
                checkedRows = checkedRows.filter(item => ['0', '1', '2'].includes(item.sendStatus));
                if (!checkedRows.length) {
                    this.yh_message_warn('请勾选发送状态不为"已关闭"的邮件进行发送！');
                    return;
                }
                this.sendAgainVisible = true;
            } else if (type == 'close') {
                checkedRows = checkedRows.filter(item => item.sendStatus == '0');
                if (!checkedRows.length) {
                    this.yh_message_warn('请勾选发送状态为"待发送"的邮件进行关闭！');
                    return;
                }
                let codes = checkedRows.map(item => item.recordId);
                params = { recordIds: codes };
                requestName(params)
                    .then(() => {
                        this.yh_message_success(name + '成功');
                        this.paging.currentPage = 1;
                        this.getTableData();
                    })
                    .finally(() => {
                        // 清除导出时列表勾选项
                        this.$nextTick(() => {
                            (this.$refs['risk-table-' + this.type] as any).resetCheckRowKeys();
                        });
                    });
            }
        } else if (type == 'search') {
            this.paging.currentPage = 1;
            this.getTableData();
        }
    }

    /**
     * 表格数据
     */
    getTableData() {
        this.tableLoading = true;
        return new Promise((resolve, reject) => {
            this.requestTableMethodName({
                ...this.searchParam,
                paging: this.paging,
            })
                .then((res: any) => {
                    this.tableData = res.list || [];
                    this.paging.total = res.total;
                    this.tableLoading = false;
                    resolve(res);
                })
                .catch(err => {
                    this.tableLoading = false;
                    reject(err);
                });
        });
    }

    handleBtnEntryNum(obj: any): void {
        this.toEntryInfo.recordId = obj.recordId;
        this.toEntryInfo.noticeType = obj.noticeType;
        this.pagingEntryDetail.currentPage = 1;
        this.entryDetailVisible = true;
        this.pagechangeEntryDetail();
    }

    handleDialogButton(type: string) {
        if (type == 'cancel') {
            this.sendAgainVisible = false;
            this.handleDialogButton('reset');
        } else if (type == 'confirm') {
            let checkedRows = (this.$refs['risk-table-' + this.type] as VueObject).checkedRows || [];
            checkedRows = checkedRows.filter(item => ['0', '1', '2'].includes(item.sendStatus));
            let params = checkedRows.map(item => {
                return {
                    recordId: item.recordId,
                    noticeType: item.noticeType,
                };
            });
            API.recordSendEmail({
                notifier: this.sendForm.notifier,
                noticeCCuser: this.sendForm.noticeCCuser,
                noticeUser: this.sendForm.noticeUser,
                recordEmailRequests: params,
                type: '2',
            })
                .then(() => {
                    this.yh_message_success('发送成功');
                    this.paging.currentPage = 1;
                    this.getTableData();
                })
                .finally(() => {
                    this.sendAgainVisible = false;
                    // 清除导出时列表勾选项
                    this.$nextTick(() => {
                        (this.$refs['risk-table-' + this.type] as any).resetCheckRowKeys();
                    });
                    this.handleDialogButton('reset');
                });
        } else if (type == 'reset') {
            const $form = this.$refs['sendForm'] as any;
            $form.resetFields();
        } else if (type == 'entry-detail-cancel') {
            this.entryDetailVisible = false;
        }
    }

    // 条目明细分页
    pagechangeEntryDetail() {
        this.entryTableLoading = true;
        API.getDetailsList({
            noticeType: this.toEntryInfo.noticeType,
            recordId: this.toEntryInfo.recordId,
            paging: this.pagingEntryDetail,
        })
            .then((res: any) => {
                this.entryDetailList = res.list;
                this.pagingEntryDetail.total = res.total;
            })
            .finally(() => {
                this.entryTableLoading = false;
            });
    }
}
</script>
<style lang="scss" scoped>
.content {
    padding: 5px;
}
.noOpened /deep/ .vxe-table {
    .vxe-table--body-wrapper.body--wrapper {
        height: calc(100vh - 270px) !important;
    }
    a {
        color: #578bec;
        padding: 0 5px;
    }
}

.header-content {
    display: flex;
    justify-title: space-between;
    align-items: center;
    background-color: #fff;
    column-gap: 10px;
    .btn {
        display: flex;
    }
}

#header-query {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    /deep/ .el-form-item {
        margin-bottom: 4px;
        .el-form-item__label {
            color: black;
            padding-right: 2px;
        }
    }
}

/deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light {
    display: flex;
    align-items: center;
    width: 65%;
    max-width: fit-content;
    padding-right: 5px;
    padding-left: 0px;
    margin: 2px 0 2px 2px;
    .el-select__tags-text {
        display: inline-block;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
}
/deep/ .el-select__tags {
    flex-wrap: nowrap;
}
.entry-detail /deep/ .el-dialog .el-dialog__body {
    height: 50vh;
}
.form /deep/ .el-select {
    width: 80%;
}
</style>
